#ifndef SOCKET_H
#define SOCKET_H

#ifdef WIN32
#pragma comment(lib, "ws2_32.lib")
#include <winsock2.h>				
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#endif

#include "SocketAddress.h"
#include "../Utils/ByteArray.h"
#include "../Connection/Connection.h"




class Socket
{
public:

	static int const			SOCKET_TCP			= SOCK_STREAM;
	static int const			SOCKET_UDP			= SOCK_DGRAM;

	static int const			SELECT_READ			= 0;
	static int const			SELECT_WRITE		= 1;

private:

	static unsigned int const	RESPONSE_TIMEOUT	= 20 * 1000;
	static unsigned int const	MAX_MESSAGE_LENTH	= 65536;

	static bool		m_isInitWinSock;
	static int		m_socketCounter;

	
	SocketAddress*	address;
	int				socketType;

	ByteArray*		m_data;
	char			buff[MAX_MESSAGE_LENTH];

public:

#ifdef WIN32
	SOCKET			m_socket;
#else
	int				m_socket;
#endif
	
	Socket(int type, const char* ip, unsigned short port);
#ifdef WIN32
	Socket(SOCKET sock, sockaddr_in address);
#else
	Socket(int sock, sockaddr_in address);
#endif
	~Socket();
  	
	void		Listen(int maxConnections = 10);
	Socket*		Accept();
	bool		Select(int mode);
	void		Disconnect();
	bool		NonBlock();
	bool		isAlive();
	SocketAddress*	getAddress() { return address; }

	void		sendByteArray(ByteArray* data);	// send message
	int			recvByteArray();
	int			Recv(char* data);
	void		Send(char* data, int len);
	int			getDesc() {return m_socket;}

	ByteArray*	getBuffer();
};

#endif // SOCKET_H
